from celery import Celery

from Bquge import Biqu

urls = 'http://www.xbiquge.la'

# poop = Biqu()
# print(poop.Nav(urls=urls))
import os, sys
# 将django项目根目录加入环境变量
parent_path = os.path.dirname(r'C:\Users\Administrator\Desktop\biquge\qugepro\qugepro')
print(parent_path)
sys.path.append(parent_path)
# 引入django配置文件
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "qugepro.settings")
# 启动django
import django
django.setup()
# 操纵数据库
from demo.models import NavInfo
from demo.models import FictionInfo
from demo.models import ZhangjieInfo,TextInfo

resut = FictionInfo.objects.all()
app = Celery('tasks', broker='redis://localhost:6379/1',backend='redis://localhost:6379/2')
@app.task
#储存导航
def nav_db():

    nav = Biqu()
    data =nav.Nav(urls=urls)
    for i in data:
        resut = NavInfo.objects.create(id=i[2],name=i[1],nhref=i[0])#添加导航
        if resut:
            print('导航(小说类型)名字成功')

        fic_db(i[0],i[2])

#储存小说名字
def fic_db(navs_href,nav_id):
    fic = Biqu()
    data = fic.Fiction(navs_href,nav_id)
    for i in data:
        fic_name(i[2],i[0],nav_id)
#爬取所有从小说信息
def fic_name(fiction_href,fiction_id,nav_id):
    Zhang = Biqu()
    data = Zhang.gic_names(fiction_href, fiction_id,nav_id)
    for i in data:

        # print(i)
        resut = FictionInfo.objects.create(
                                            id=i[0],
                                            fiction_title=i[1],
                                           fiction_href=i[2],
                                           jianjie=i[3],
                                           author=i[4],
                                           images=i[5],
                                           create_time=i[6],
                                           navid_id=i[7],

                                            )
        if resut:
            print('小说详细储存成功')

        zhangjie_name(i[2],i[0])



#储存章节
def zhangjie_name(hrefs,fiction_id):
    texts = Biqu()
    data = texts.zhangjie_name(hrefs,fiction_id)
    for i in data:
        print(i)

        resut = ZhangjieInfo.objects.create(id=i[0],title=i[1],hrefs=i[2],fiction_id=fiction_id)
        if resut:
            print('小说跟章节储存成功')
        text_name(i[0], i[2])

def text_name(zhangjie_id,hrefs):
    texts = Biqu()
    data = texts.text_name(zhangjie_id,hrefs)
    for i in data:
        rest = TextInfo.objects.create(titles=i[1],font=i[2],zhangje_id=zhangjie_id)
        if rest:
            print('小说内容储存成功')

@app.task
def start():
    nav_db()
#
# if __name__=="__main__":
#     nav_db()








